package com.gzcstec.order.controller;

import com.gzcstec.order.convert.OrderFormConvertOrderDTO;
import com.gzcstec.order.dto.OrderDTO;
import com.gzcstec.order.enums.ExceptionCodeEnums;
import com.gzcstec.order.exception.OrderException;
import com.gzcstec.order.form.OrderForm;
import com.gzcstec.order.service.OrderService;
import com.gzcstec.order.utils.ResultUtils;
import com.gzcstec.order.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 1.参数校验
     * 1.查询商品信息
     * 2.计算商品总额
     * 4.订单详情进库
     * 3.订单主表进库
     */
    //增加熔断配置，读取配置信息
    @PostMapping("/buyer/create")
    public ResultVO<Map<String,String>> create(@Valid OrderForm orderForm ,
                                               BindingResult bindingResult) {

        if(bindingResult.hasErrors()) {
            //参数有误
            log.error("【订单创建】订单数据不正确，orderForm={}" , orderForm);
            throw new OrderException(ExceptionCodeEnums.PARAM_ERROR ,
                    bindingResult.getFieldError().getDefaultMessage());
        }

        //校验通过
        //orderForm -> orderDTO
        OrderDTO orderDTO = OrderFormConvertOrderDTO.convert(orderForm);
        orderDTO = orderService.create(orderDTO);

        Map<String,String> result = new HashMap<>();
        result.put("orderId" , orderDTO.getOrderId());
        return ResultUtils.success(result);

    }

    @PostMapping("/seller/finish")
    public ResultVO finish(@RequestParam("orderId") String orderId) {
        return ResultUtils.success(orderService.finish(orderId));
    }

}
